﻿create function [String].[Capitalize] ( @p_String nvarchar(max) )
returns nvarchar(max) as
begin

  declare @Index int = 2;
  declare @Char char(1);
  declare @returnString nvarchar(max) = Stuff( Lower( @p_String ), 1, 1, Upper( SubString( @p_String, 1, 1 ) ) );
  
  while @Index <= Len( @p_String )
  begin
    set @Char = SubString( @p_String, @Index, 1 );
    if @Char in (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')
    begin
      if @Index + 1 <= Len( @p_String )
      begin
        if @Char != '''' or RTrim( Upper( SubString( @p_String, @Index + 1, 2 ) ) ) != 'S'
        begin
          set @returnString = Stuff( @returnString, @Index + 1, 1, Upper( SubString( @p_String, @Index + 1, 1) ) )
        end
      end
    end
    set @Index = @Index + 1
  end
  
  return IsNull( @returnString, '' )

end